package com.jpa.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

import com.alibaba.dubbo.config.annotation.Service;
import com.jpa.bean.PageBean;
import com.jpa.bean.PageBeanTwo;
import com.jpa.dao.IAffairsDao;
import com.jpa.entity.Affairs;
import com.jpa.entity.Useradmin;
import com.jpa.service.AffairsService;

@Service(version = "1.0.0", interfaceName = "AffairsService")
public class AffairsServiceImpl implements AffairsService {
	@Autowired
	private IAffairsDao ad;

	@Override
	@Cacheable(value = "findAffairsAll", unless = "#result eq null")
	public PageBean findAffairsAll(PageBeanTwo two) {
		// TODO Auto-generated method stub
		Pageable page = new PageRequest(two.getPage(), two.getSize(), Direction.DESC, two.getDesc());
		PageBean pageBean = new PageBean();
		Page<Affairs> page2 = ad.findAll(page);
		pageBean.setTotalElements(page2.getTotalElements());
		pageBean.setTotalPages(page2.getTotalPages());
		pageBean.setNumber(page2.getNumber());
		pageBean.setContent(page2.getContent());
		return pageBean;
	}

	@Override
	@Cacheable(value = "findAll", unless = "#result eq null")
	public List<Affairs> findAll() {
		// TODO Auto-generated method stub
		return ad.findAll();
	}

	@Override
	@Cacheable(value = "findAffairsByTitleLike", unless = "#result eq null")
	public List<Affairs> findAffairsByTitleLike(String title, PageBeanTwo two) {
		// TODO Auto-generated method stub
		Pageable page = new PageRequest(two.getPage(), two.getSize(), Direction.DESC, two.getDesc());
		return ad.findByTitleLike(title, page);
	}

	@Override
	@Cacheable(value = "findAffairsById", unless = "#result eq null")
	public List<Affairs> findAffairsById(Long id) {
		// TODO Auto-generated method stub
		return ad.findById(id.intValue());
	}

	@Override
	@CacheEvict(value = "find*", allEntries = true, beforeInvocation = true)
	public boolean save(Affairs affairs) {
		// TODO Auto-generated method stub
		try {
			Affairs a=new Affairs();
			a.setTitle(affairs.getTitle());
			if (findOne(a) == null) {
				ad.save(affairs);
				return true;
			} else {
				return false;
			}
		} catch (

		Exception e)

		{
			// TODO: handle exception
			return false;
		}

	}

	@Override
	@Cacheable(value = "findOne", unless = "#result eq null")
	public Affairs findOne(Affairs affairs) {
		// TODO Auto-generated method stub
	//	affairs.setUseradmin(null);
		Example<Affairs> example = Example.of(affairs);
		return ad.findOne(example);
	}

}
